package lrscp.lib;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import lrscp.lib.io.MFileUtils;

public class MConfig {
    static final Pattern itemPat = Pattern.compile("([^= ]+)=(.+)");

    public static Map<String, String> readConfig(File fd) {
        Map<String, String> map = new HashMap<String, String>();
        try {
            fd.createNewFile();
            List<String> lines = MFileUtils.readLines(fd);
            for (String line : lines) {
                Matcher matcher = itemPat.matcher(line);
                if (matcher.find()) {
                    String key = matcher.group(1);
                    String value = matcher.group(2);
                    if (map.containsKey(key)) {
                        Log.e("redefined key:" + key);
                    } else {
                        // Log.p("get key:" + key + " value:" + value);
                        map.put(key, value);
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return map;
    }

    public static void writeConfig(File fd, Map<String, String> map) {
        try {
            fd.createNewFile();
            FileWriter fw = new FileWriter(fd);
            for (Entry<String, String> e : map.entrySet()) {
                fw.append(e.getKey() + "=" + e.getValue() + "\r\n");
            }
            fw.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }

    public static int getInt(Map<String, String> map, String key, int defaultValue) {
        try {
            if (map.containsKey(key))
                return Integer.valueOf(map.get(key));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return defaultValue;
    }

    public static void main(String[] args) throws IOException {
        Map<String, String> map = new HashMap<String, String>();
        map.put("hello", "world");
        map.put("2", "3");
        File fd = new File("config.txt");
        writeConfig(fd, map);
        for (Entry<String, String> e : readConfig(fd).entrySet()) {
            Log.i("get key:" + e.getKey() + " value:" + e.getValue());
        }
    }
}
